package filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
//        chain.doFilter(request, response);
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;

        String [] urls = {"/login.jsp","/register.jsp",
                "/css","/images","/js","/login","/user","/verifyCode"};
        String uri = req.getRequestURI();
        for (String u : urls){
            if (uri.contains(u)){
                chain.doFilter(req,resp);
                return;
            }
        }




//1. 判断session中是否有user
        HttpSession session = req.getSession();
        Object user = session.getAttribute("LOGIN_USER");
        //2. 判断user是否为null
        if(user != null){
// 已经登录,放行
            chain.doFilter(req, resp);
        }else {
// 没有登陆，存储提示信息，跳转到登录页面
            req.setAttribute("LOGIN_MSG","您尚未登陆！");
            req.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }

    }
}
